package com.xc.tool.utils;

import com.esotericsoftware.reflectasm.MethodAccess;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: Ip工具类</p>
 * <p>创建人: 小程</p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/7/1</p>
 *
 * @version v1.0
 */
public class IpUtils {

    /**
     * <p>功能描述: 获取客户端Ip地址</p>
     * <p>更新人: 小程</p>
     * <p>更新描述: 添加方法</p>
     * <p>更新人邮箱: 779943476@qq.com</p>
     * <p>更新时间: 2019/7/1</p>
     *
     * @param request 传入HttpServletRequest
     * @return 返回客户端Ip
     */
    public static String getClientIp(Object request) {
        MethodAccess methodAccess = MethodAccess.get(request.getClass());
        String ip = (String) methodAccess.invoke(request, "getHeader", "X-Read-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getHeader", "x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getHeader", "Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getHeader", "WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getHeader", "HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getHeader", "HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = (String) methodAccess.invoke(request, "getRemoteAddr");
        }
        // 去掉阿里云的高防IP代理转发导致的IP增多问题,电信：180.97.88.0/24 联通：218.60.120.0/24
        if (ip.indexOf(",") > 0) {
            // 按照网络协议，原则上是取第一个IP才是真实的
            ip = ip.substring(0, ip.indexOf(","));
        }
        return ip;
    }
}
